package com.yzq.api.aliyunai;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.yzq.api.aliyunai.constant.AliyunQianWenModelUrl;
import com.yzq.api.aliyunai.model.AITaskResponse;
import com.yzq.api.aliyunai.model.AIResponse;
import com.yzq.enums.ErrorCode;
import com.yzq.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AliyunApiAi {

    @Value("${aliyun.ai.apiKey}")
    private String apiKey;


    /**
     * 创建任务
     * @param request 创建文生图任务参数
     * @return 任务id
     */
    public String createTask(Object request, String model) {
        if(request == null) {
            throw new BusinessException(ErrorCode.BAD_REQUEST, "参数异常");
        }
        log.info("创建任务参数: {}", request);
        HttpRequest httpRequest = HttpRequest.post(model)
                .header("X-DashScope-Async", "enable")
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(request));
        try(HttpResponse httpResponse = httpRequest.execute()) {
            log.info("创建任务结果: {}", httpResponse.body());
            if(!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.SERVICE_UNAVAILABLE, "创建任务失败");
            }
            AITaskResponse aliyunImageGenerateTaskResponse = JSON.parseObject(httpResponse.body(), AITaskResponse.class);
            if(aliyunImageGenerateTaskResponse.getCode() != null) {
                throw new BusinessException(ErrorCode.SERVICE_UNAVAILABLE, "创建任务失败");
            }
            return aliyunImageGenerateTaskResponse.getOutput().getTaskId();
        }
    }

    /**
     * 获取任务结果
     * @param taskId 任务id
     * @return 任务结果
     */
    public AIResponse getTextToImageResult(String taskId) {
        HttpRequest httpRequest = HttpRequest.get(String.format(AliyunQianWenModelUrl.GET_TASK_RESULT_URL, taskId))
                .header("Authorization", "Bearer " + apiKey);
        try(HttpResponse httpResponse = httpRequest.execute()) {
            if(!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.SERVICE_UNAVAILABLE, "AI任务结果失败");
            }
            AIResponse imageGenerateResponse = JSON.parseObject(httpResponse.body(), AIResponse.class);
            if(imageGenerateResponse.getCode() != null) {
                throw new BusinessException(ErrorCode.SERVICE_UNAVAILABLE, "AI任务结果失败");
            }
            return imageGenerateResponse;
        }

    }
}